package com.flute.framework;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.flute.framework.configuration.FluteInformation;
import com.flute.framework.configuration.FluteXMLConverter;
import com.flute.framework.exception.ConfigurationParseException;
import com.flute.framework.index.IIndexer;
import com.flute.framework.index.TimerIndexer;
import com.flute.framework.search.ISearcher;

public class Flute {
	private Map<String, ISearcher> searcherMap = new HashMap<String, ISearcher>();
	private Map<String, TimerIndexer> indexerMap = new HashMap<String, TimerIndexer>();
	private static Flute instance;

	public synchronized static Flute getInstance()
			throws ConfigurationParseException {
		if (instance == null) {
			instance = new Flute();
		}

		return instance;
	}

	private Flute() throws ConfigurationParseException {
		initial();
	}

	private void initial() throws ConfigurationParseException {
		URL url = Flute.class.getClassLoader().getResource("config/flute");
		if (url == null) {
			throw new ConfigurationParseException("找不到flute配置文件.");
		}
		String path = url.getPath();
		if (StringUtils.isEmpty(path)) {
			throw new ConfigurationParseException(path + "路径不正确，请检查后再试");
		}
		File file = new File(path);
		File[] files = file.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isFile() && isXmlFile(f)) {
					String absolutePath = f.getAbsolutePath();
					FluteInformation info = FluteXMLConverter
							.fluteInformationFromFile(absolutePath);
					TimerIndexer timerIndexer = info.getTimerIndexer();
					if (timerIndexer != null) {
						IIndexer indexer = timerIndexer.getIndexer();
						if (indexer != null) {
							indexerMap.put(indexer.getIndexerName(), timerIndexer);
						}
					}
					
					List<ISearcher> searcherList = info.getSearcherList();
					if (searcherList != null) {
						for (ISearcher searcher : searcherList) {
							if (searcher.getSearcherProvider() == null) {
								searcher.setSearcherProvider(info.getProvider());
							}
							searcherMap.put(searcher.getSearcherName(), searcher);
						}

					}
				}
			}
		}
	}

	private boolean isXmlFile(File f) {
		return f.getName().endsWith(".xml");
	}

	public ISearcher getSearcher(String name) {
		return searcherMap.get(name);
	}

	public TimerIndexer getIndexer(String name) {
		return indexerMap.get(name);
	}

	public String[] getAllSearchers() {
		return searcherMap.keySet().toArray(new String[] {});
	}

	public boolean isValidSearcher(String searcher) {
		return searcherMap.containsKey(searcher);
	}

	public String[] getAllIndexs() {
		return indexerMap.keySet().toArray(new String[] {});
	}

	public boolean isValidIndex(String index) {
		return indexerMap.containsKey(index);
	}

}
